package com.atguigu.yygh.gateway.filter;

/**
 * @Author:hx
 * @DateTime:2022/11/9 14:11
 * @Description:
 */
/*@Component
public class LoginGlobalFilter implements GlobalFilter, Ordered {

    private AntPathMatcher antPathMatcher=new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getURI().getPath();
        if (antPathMatcher.match("/admin/user/**",path)){
            return chain.filter(exchange);//放行
        }else if (antPathMatcher.match("/admin/**",path)){
            List<String> strings = request.getHeaders().get("X-Token");
            if (strings != null){
                if (strings.get(0).equals("admin-token")){
                    return chain.filter(exchange);
                }
            }
            response.setStatusCode(HttpStatus.SEE_OTHER);
            //路由跳转：
            response.getHeaders().set(HttpHeaders.LOCATION,"http://localhost:9528");
            return response.setComplete();//结束请求
        }
        return out(response);
    }

    @Override
    public int getOrder() {
        return 0;
    }

    private Mono<Void> out(ServerHttpResponse response) {
        JsonObject jsonObject=new JsonObject();
        jsonObject.addProperty("code","20001");
        jsonObject.addProperty("message","路径有误");
        jsonObject.addProperty("success","false");
        byte[] bits =jsonObject.toString().getBytes(StandardCharsets.UTF_8);

        DataBuffer buffer = response.bufferFactory().wrap(bits);
        response.setStatusCode(HttpStatus.NOT_FOUND);
        //指定编码，否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }
}*/
